package com.suyeer.basic.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;

import java.util.concurrent.*;

/**
 * @author jun 2018/12/3.
 */
public class ExecutorUtil {
    private static ExecutorService executorService1 = Executors.newSingleThreadExecutor();

    public static ExecutorService newCachedThreadPool() {
        return newCachedThreadPool(0, 10, 60L, null);
    }

    public static ExecutorService newCachedThreadPool(String poolName) {
        return newCachedThreadPool(0, 10, 60L, poolName);
    }

    public static ExecutorService newCachedThreadPool(int corePoolSize,
                                                      int maximumPoolSize,
                                                      long keepAliveTime,
                                                      String poolName) {
        poolName = StringUtils.defaultIfBlank(poolName, "cached-thread-pool") + "-%d";
        return new ThreadPoolExecutor(corePoolSize, maximumPoolSize,
                keepAliveTime, TimeUnit.SECONDS,
                new SynchronousQueue<Runnable>(),
                new BasicThreadFactory.Builder().namingPattern(poolName).daemon(true).build());
    }

    public static ExecutorService newFixedThreadPool(int nThreads) {
        return newFixedThreadPool(nThreads, null);
    }

    public static ExecutorService newFixedThreadPool(int nThreads, String poolName) {
        poolName = StringUtils.defaultIfBlank(poolName, "fixed-thread-pool") + "-%d";
        return new ThreadPoolExecutor(nThreads, nThreads,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(),
                new BasicThreadFactory.Builder().namingPattern(poolName).daemon(true).build());
    }

    public static ExecutorService newSingleThreadExecutor() {
        return newSingleThreadExecutor("single-thread-pool");
    }

    public static ExecutorService newSingleThreadExecutor(String poolName) {
        return newFixedThreadPool(1, poolName);
    }

    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return newScheduledThreadPool(corePoolSize, null);
    }

    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, String poolName) {
        poolName = StringUtils.defaultIfBlank(poolName, "scheduled-thread-pool") + "-%d";
        return new ScheduledThreadPoolExecutor(corePoolSize, new BasicThreadFactory.Builder().namingPattern(poolName).daemon(true).build());
    }

}
